import http from "node:http"; // 导入http模块
import fs from "node:fs"; // 导入文件系统模块
import path from "node:path"; // 导入路径处理模块
import mime from "mime"; // 导入mime模块
const server = http.createServer(function (req, res) {
  const { url, method } = req;
  //处理静态资源
  if (method === "GET" && url.startsWith("/static")) {
    const filePath = path.join(process.cwd(), url); //process.cwd()：获取当前进程执行的目录
    const mimeType = mime.getType(filePath); //获取文件mime类型
    console.log("mimeType", mimeType);
    fs.readFile(filePath, function (err, data) {
      if (err) {
        res.writeHead(404, {
          "Content-Type": "text/plain;charset=utf8",
        });
        res.end("not found");
      } else {
        console.log("来了老弟？");
        res.writeHead(200, {
          "Content-Type": mimeType, //mimi 类型 css:text/css html:text/html
          "cache-Control": "public,max-age=3600", //设置缓存控制 缓存分为 disk-cache 硬盘缓存 和 memory-cache 内存缓存 刷新页面会从硬盘缓存中读取
        });
        res.end(data);
      }
    });
  }
  // 处理动态资源
  if ((method === "GET" || method === "POST") && url.startsWith("/api")) {
    // ...处理动态资源的逻辑
  }
});
server.listen(8080, () => {
  console.log(" 服务器启动成功");
});
